import 'package:app/core/rtc/base/call_state.dart';
import 'package:app/core/rtc/impl/session.dart';
import 'package:app/core/utils/helpers/log_print.dart';
import 'package:app/data/services/rtc_service.dart';
import 'package:app/data/services/store_service.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:get/get.dart';

import 'state.dart';

class RtcLogic extends GetxController {
  final state = RtcState();
  StoreService _storeService = Get.find<StoreService>();
  String remark;

  @override
  void onInit() {
    _initRender();
    super.onInit();
  } //

  updateLocalStream(Session session, MediaStream localStream) {
    state.localRender.value.srcObject = localStream;
    update();
  }

  updateRemoteStream(Session _session, MediaStream remoteStream) {
    state.remoteRender.value.srcObject = remoteStream;
    state.callPeerID.value = _session.pid;
    update();
    _storeService.database
        .queryFriendByPhone(state.callPeerID.value)
        .then((value) {
      remark = value[0].remark ?? value[0].userName;
    });
  }

  rtcCall(String callPhone, String sessionType) {
    state.callPeerID.value = callPhone;
    state.isCalling.value = true;
    _call(callPhone, sessionType);
  }

  _call(String callPhone, String type) {
    RtcService.instance.rtcSignaling.requestCall(callPhone, type);
  }

  _initRender() async {
    await state.localRender.value.initialize();
    await state.remoteRender.value.initialize();
  }

  switchCamera() {
    RtcService.instance.rtcSignaling.switchCamera();
  }

  muteMicroPhone() {
    RtcService.instance.rtcSignaling.muteMicroPhone();
    state.isMuteMic.value = !state.isMuteMic.value;
  }

  //
  endCall() {
    RtcService.instance.rtcSignaling.endCall(state.callPeerID.value);
    release();
    Get.back(closeOverlays: true);
  }

  cancelCall(CallState endStrategy) {
    RtcService.instance.rtcSignaling
        .endCall(state.callPeerID.value, isSelfCancel: true);
    release();
    Get.back(closeOverlays: true);
  }

  release() {
    state.isCalling?.value = false;
    state.localRender?.value?.srcObject = null;
    state.remoteRender?.value?.srcObject = null;

    update();
  }

  @override
  void onClose() {
    LogPrint.getInstance().printError(" RtcLogic onClose ");
    state.localRender?.value?.dispose();
    state.remoteRender?.value?.dispose();
    release();
    super.onClose();
  }
}
